﻿using Account.Api.Client;
using Account.Api.Dtos;
using BootstrapBlazor.Components;
using Cyss.Core;
using CyssBlazor.Shared.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CyssBlazor.Shared.Pages.AccountManager.Depts
{
    public partial class List
    {
        private Table<DepartmentTreeModel> table;
        protected async override Task OnAfterRenderAsync(bool firstRender)
        {
            await base.OnAfterRenderAsync(firstRender);
        }
        private DepartmentModel CurrentDepartmentModel { set; get; }

        public DepartmentSearchModel searchModel { set; get; } = new DepartmentSearchModel();

        private IList<DepartmentModel> DepartmentModels { set; get; }

        /// <summary>
        ///数据查询方法
        /// </summary>
        /// <param name="options"></param>
        /// <returns></returns>
        protected async Task<QueryData<DepartmentTreeModel>> OnQueryAsync(QueryPageOptions options)
        {
            //TODO: 此处代码后期精简
            searchModel.pageIndex = options.PageIndex;
            searchModel.pageSize = options.PageItems;
            searchModel.SearchName = options.SearchText;
            var apiResponse = await AccountClientFactory.Dept.GetPageListDepartments(searchModel);
            if (apiResponse.IsSuccess && apiResponse.Data != null)
            {
                DepartmentModels = apiResponse.Data.Data.ToList(); ;
                return await Task.FromResult(new QueryData<DepartmentTreeModel>()
                {
                    Items = apiResponse.Data.Data.Where(x => x.ParentDeptId == 0).OrderBy(x => x.DisplayOrder).Select(x => { var m = x.ToObject<DepartmentTreeModel>(); m.HasChildren = true; return m; }),
                    TotalCount = apiResponse.Data.Total
                });
            }
            return null;
        }
        //private async Task<IEnumerable<TableTreeNode<DepartmentTreeModel>>> OnTreeExpandQuary(DepartmentTreeModel foo)
        //{
        //    var list = DepartmentModels.Where(f => f.ParentDeptId == foo.Id).OrderBy(x => x.DisplayOrder).Select(x => x.ToObject<DepartmentTreeModel>()).ToList();
        //    foreach (var dept in list)
        //    {
        //        if (DepartmentModels.Any(x => x.ParentDeptId == dept.Id))
        //        {
        //            dept.HasChildren = true;
        //        }
        //    }
        //    return await Task.FromResult(list);
        //}

        private async Task<IEnumerable<TableTreeNode<DepartmentTreeModel>>> TreeNodeConverter(IEnumerable<DepartmentTreeModel> items)
        {
            // 构造树状数据结构
            var ret = BuildTreeNodes(items);
            return await Task.FromResult(ret);

            IEnumerable<TableTreeNode<DepartmentTreeModel>> BuildTreeNodes(IEnumerable<DepartmentTreeModel> items)
            {
                var ret = new List<TableTreeNode<DepartmentTreeModel>>();
                ret.AddRange(items.OrderBy(x => x.DisplayOrder).Select((foo, index) => new TableTreeNode<DepartmentTreeModel>(foo)
                {
                    // 此处为示例，假设偶行数据都有子数据
                    HasChildren =foo.HasChildren,
                    // 如果子项集合有值 则默认展开此节点
                    IsExpand =false,
                    // 获得子项集合
                    Items = BuildTreeNodes(foo.Children)
                }));
                return ret;
            }


        }

        protected async Task<bool> OnSaveAsync(DepartmentModel options, ItemChangedType itemChangedType)
        {
            if (options.Id == 0)
            {
                var apiResponse = await AccountClientFactory.Dept.CreateDepartment(options);
                return apiResponse.IsSuccess;
            }
            else
            {
                var apiResponse = await AccountClientFactory.Dept.EditDepartment(options);
                return apiResponse.IsSuccess;
            }
        }

        protected async Task<bool> OnDeleteAsync(IEnumerable<DepartmentModel> options)
        {
            var apiResponse = await AccountClientFactory.Dept.DeleteDepartment(options.FirstOrDefault().Id);
            return apiResponse.IsSuccess;
        }


        private async Task CreateChildrenDept(DepartmentTreeModel department)
        {
            this.ShowModal<CreateOrUpdate, DepartmentTreeModel>("创建子部门", department, 1200);
            await Task.CompletedTask;
        }

        protected async Task OnCallbackAsync(object si)
        {
            await table.QueryAsync();
        }
    }
    public class DepartmentTreeModel : DepartmentModel
    {
        public IEnumerable<DepartmentTreeModel>? Children { get; set; }

        public bool IsMenu { set; get; }

        public bool HasChildren { get; set; }
    }
}
